<?php
//消费券及领取操作

namespace App\Repositories;

use App\Models\RiskModel;
use App\Models\RiskCheckModel;
use http\Env\Request;
use Illuminate\Support\Arr;


class RiskRepository extends BaseRepository
{
    public function __construct()
    {

    }

    /**
     * 配置搜索条件
     * @param $params
     * @return array[]
     */
    public function getFilter ($params) {
        $user = request()->user();
        $where = [];
        $where[] = [
            'admin_id', $user['id']
        ];
        return [
            'where' => $where,
        ];
    }

    /**
     * 获取列表
     * @param $params
     * @return array
     */
    public function getList ($params)
    {
        $filter = $this->getFilter($params);
        $orders = $this->_getOrders($params);
        $lists = $this->getListItems(RiskModel::query(), $filter, $params['page_size'] ?? 20, ['*'], 'page', $orders);
        return $lists;
    }

    /**
     * @param $params
     * @return mixed
     */
    public function save ($params)
    {
//        $params = $this->formatSaveParams($params);
        return $this->saveOrUpdate('RiskModel', $params);
    }

    /**
     * @param $params
     * @return array
     */
    public function getCheckList ($params)
    {
        $filter = $this->getFilter($params);
        $orders = $this->_getOrders($params);
        $lists = $this->getListItems(RiskCheckModel::query(), $filter, $params['page_size'] ?? 20, ['*'], 'page', $orders);
        return $lists;
    }

    public function saveRisk ($params, $user)
    {
        $saveData = $this->_formatRiskSaveParams($params);
        $saveData['admin_id'] = $user['id'];
        return $this->saveOrUpdate('RiskModel', $saveData);
    }

    private function _formatRiskSaveParams ($params)
    {
        $date = Date('Y-m-d H:i:s');
        // 获取第一个的baseField
        $baseField = RiskModel::where('id', 1)
            ->value('base_field');
        $params['base_field'] = $baseField;
        $params = $this->_getCustomizeFieldOptionsValue($params);
        $params['created_at'] = $params['updated_at'] = $date;
        return $params;
    }

    private function _getCustomizeFieldOptionsValue ($params)
    {
        $customizeField = json_decode($params['customize_field'], true);
        foreach ($customizeField as $key => $field) {
            $options = $field['field']['props']['options'];
            $value = 1;
            foreach ($options as $optionKey => $option) {
                $customizeField[$key]['field']['props']['options'][$optionKey]['value'] = $value;
                $value++;
            }
        }
        $params['customize_field'] = json_encode($customizeField);
        return $params;
    }

    /**
     * @param $params
     * @return mixed
     */
    public function saveRiskCheck ($params, $user)
    {
        $saveData = $this->_formatRiskCheckSaveParams($params, $user['id']);
        return $this->saveOrUpdate('RiskCheckModel', $saveData);
    }

    /**
     * @param $params
     */
    public function _formatRiskCheckSaveParams ($params, $adminId)
    {
        $risk = RiskModel::find($params['risk_id']);
        $customizeFields = json_decode($risk['customize_field'], true);
        $totalScore = 0;
        foreach ($customizeFields as $customizeField) {
            $maxScore = $this->getMaxScore($customizeField);
            $totalScore += $maxScore;
        }
        $fieldColumnValues = $this->getFieldColumnValues($params);
        $followRepo = new FollowRepository();
        $divisorScore = $this->_getDividendScore($fieldColumnValues['customizeFieldColumnValues'], $customizeFields);           // 10为基本信息中所属策略的分数
        if ($totalScore == 0) {
            $score = 0;
        } else {
            $score = number_format($divisorScore / $totalScore, 2) * 100;
        }
        $saveData = [
            'score' => $score,
            'admin_id' => $adminId,
            'risk_id' => $params['risk_id'],
            'stock_name' => $params['stock_name'],
            'stock_code' => $params['stock_code'],
            'base_field' => $risk['base_field'],
            'customize_field' => $risk['customize_field'],
            'code_prefix' => $followRepo->getStockPrefixByCode($params['stock_code']),
            'base_field_colunm_value' => json_encode($fieldColumnValues['baseFieldColumnValues']),
            'customize_field_column_values' => json_encode($fieldColumnValues['customizeFieldColumnValues']),
        ];
        return $saveData;
    }

    private function _getDividendScore ($customizeValues, $customizeFields)
    {
        $divisorScore = 0;
        foreach ($customizeValues as $customizeField => $customizeValue) {
            if (isset($customizeFields[$customizeField])) {
                $options = $customizeFields[$customizeField]['field']['props']['options'];
                $options = Arr::keyBy($options, 'value');
                $divisorScore += $options[$customizeValue]['score'];
            }
        }
        return $divisorScore;
    }

    /**
     * @param $params
     * @return array
     */
    private function getFieldColumnValues ($params)
    {
        unset($params['strategy_id']);
        $customizeFieldColumnValues = $this->getCustomizeFieldColumnValues($params);
        return [
          'baseFieldColumnValues' => [
              'stock_code' => $params['stock_code'],
              'stock_name' => $params['stock_name'],
          ],
          'customizeFieldColumnValues' => $customizeFieldColumnValues,
        ];
    }

    /**
     * @param $params
     * @return array
     */
    private function getCustomizeFieldColumnValues ($params)
    {
        $customizeFieldColumnValues = [];
        foreach ($params as $key => $param) {
            if (str_contains($key, 'customize_')) {
                $customizeFieldColumnValues[$key] = $param;
            }
        }
        return $customizeFieldColumnValues;
    }

    /**
     * @param $customizeField
     * @return int|mixed
     */
    private function getMaxScore ($customizeField)
    {
        $maxScore = 0;
        foreach ($customizeField['field']['props']['options'] as $option) {
            if ($option['score'] > $maxScore) {
                $maxScore = $option['score'];
            }
        }
        return $maxScore;
    }

    /**
     * @param $params
     * @param $user
     * @return array
     */
    public function getRiskCheckDetail ($params, $user)
    {
        $riskCheck = RiskCheckModel::where('id', $params['id'])
            ->where('admin_id', $user['id'])
            ->first();
        $customizeField = json_decode($riskCheck['customize_field'], true);
        $baseField = json_decode($riskCheck['base_field'], true);
        $baseFieldColunmValue = json_decode($riskCheck['base_field_colunm_value'], true);
        $customizeFieldColumnValues = json_decode($riskCheck['customize_field_column_values'], true);
        $baseFieldWidthValue = $this->setRiskBaseFieldValue($riskCheck, $baseField, $baseFieldColunmValue);
        $customizeFieldWidthValue = $this->setRiskCustomizeFieldValue($riskCheck, $customizeField, $customizeFieldColumnValues);
        return [
            ...$baseFieldWidthValue,
            ...$customizeFieldWidthValue
        ];
    }

    /**
     * @param $riskCheck
     * @param $baseField
     * @param $baseFieldColunmValue
     * @return array
     */
    private function setRiskBaseFieldValue ($riskCheck, $baseField, $baseFieldColunmValue)
    {
        $baseField['risk_id']['field']['value'] = $riskCheck['risk']['name'];
        $baseField['stock_name']['field']['value'] = $riskCheck['stock_name'];
        $baseField['stock_code']['field']['value'] = $riskCheck['stock_code'];
        $baseField['score']['field']['value'] = $riskCheck['score'];
        return $baseField;
    }

    /**
     * @param $riskCheck
     * @param $customizeField
     * @param $customizeFieldColumnValues
     * @return mixed
     */
    private function setRiskCustomizeFieldValue ($riskCheck, $customizeField, $customizeFieldColumnValues)
    {
        $index = 0;
        $summaryValue = '';
        foreach ($customizeField as $key => &$customize) {
            $index++;
            $field = $customize['field'];
            $options = $field['props']['options'];
            foreach ($options as $option) {
                if ($option['value'] == $customizeFieldColumnValues[$key]) {
                    $customizeField[$key]['field']['value'] = $option['label'];
                    if (!empty($option['remark'])) {
                        $summaryValue .= $option['remark'] . "\n\r";
                    }
                    break;
                }
            }
        }
        $index++;
        if ($riskCheck['score'] == 100) {
            $summaryValue = '评测为满分，符合交易规则';
        } else if (count($customizeField) == 0 && count($customizeFieldColumnValues) == 0) {
            $summaryValue = '没有配置评分选项，总分为0分，风险评测没有意义，请先配置评分选项';
        } else if (empty($summaryValue)) {
            $summaryValue = '评分优良，符合交易规则';
        }
        $customizeField["customize_$index"] = [
            'item' => [
                'label' => '总结'
            ],
            'field' => [
                'type' => 'textarea',
                'value' => $summaryValue,
            ]
        ];
        return $customizeField;
    }
}
